package com.gxa.eshops.portal.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.eshops.portal.entity.domain.Goods;
import com.gxa.eshops.portal.service.GoodsCacheService;
import com.gxa.eshops.portal.utils.RestUtils;
import com.gxa.eshps.cores.common.JsonResult;
import com.gxa.eshps.cores.exception.BusinessException;
import com.gxa.eshps.cores.exception.ExceptionCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * @program: IntelliJ IDEA
 * @description:
 * @author: Mr.Wang
 * @create: 2022-07-11 09:36
 **/
@Service
@Slf4j
public class GoodsCacheServiceImpl implements GoodsCacheService {
    public static final String PRE = "goods:";
    @Autowired
    private RedisTemplate<String ,Object> redisTemplate;

    @Override
    public Object selectGoodsCache(Long id) throws Exception {
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        Object goods = opsForValue.get(PRE+id);
        if (goods != null) {
            log.info("redis获取id为{}的商品信息",id);
            return goods;
        } else {
            String url = "http://localhost:8080/goods/selectById";
            MultiValueMap<String ,Object> params = new LinkedMultiValueMap<>();
            params.add("id", id);
            //注意权限
            Map<String, Object> mysqlGoods = RestUtils.postWithParams(url, null, params);
            Object data =mysqlGoods.get("data");
            ObjectMapper objectMapper = new ObjectMapper();
            String value = objectMapper.writeValueAsString(data);
            if (data==null){
                throw new BusinessException(ExceptionCode.COURIER_SELECT_FAILED);
            }
            opsForValue.set(PRE+id,value,2, TimeUnit.HOURS);
            log.info("MySQL获取id为{}的商品信息",id);
            return data;
        }
    }


}
